//
//  JSSendvehicleGoodsController.swift
//  fho
//
//  Created by 郭颢源 on 2021/5/10.
//

import UIKit

/// 发整车 货物
class JSSendvehicleGoodsController : BaseFormsController, UITableViewDelegate, UITableViewDataSource {
    
    
    var showAll:Bool = true
    
    
    
    typealias RequestBlock = (_ arr:Array<Dictionary<String,Any>>)->Void;
    var block : RequestBlock?;
    
    func checkHaveEmptyField(block:RequestBlock) {
        
    }
    lazy var arr = [[String:Any]]()
    

    
    lazy var iconBtn:UIButton = {
        var _iconBtn = UIButton()
        _iconBtn.titleLabel!.font = UIFont.systemFont(ofSize: 16)
        _iconBtn.contentHorizontalAlignment = .center
        _iconBtn.setTitleColor(.white, for: .normal)
        _iconBtn.setTitle("添加货物", for: .normal)
        _iconBtn.backgroundColor = .systemOrange
        _iconBtn.sg_addCorner(radius: 20)
        
        _iconBtn.addTarget(self, action: #selector(subParams(_:)), for: .touchUpInside)
        return _iconBtn
    }()
    lazy var noteLab: UILabel = {
        var lab = UILabel()
        lab.textColor = .systemGray2
        lab.numberOfLines = 0
        lab.font = UIFont.systemFont(ofSize: 12)
        lab.text = "-1- 一个运单最多添加三种货物。\n-2- 添加完成请点击右上角确定提交。\n-3- 添加的货物可以左滑删除。"
        return lab
    }()
    let showModel = JSFormHeaderModel()
    @objc func subParams(_ sender:UIButton) {
        if showModel.content.count>=3 {
            JSShowMessage.showTipMsg("最多添加3个货物", time: 1)
            return
        }
        print("提交")
        print(self.uploadDict)
        let result = validateValue()
        if !result.isEmpty {
            JSShowMessage.showTipMsg(result, time: 1)
            return
        }
        
        let headerModel = self.datas[1] as? JSFormHeaderModel
        
        let model:JSFormModel = headerModel!.content[1]
        self.uploadDict["packwayType"] = model.text
        self.arr.append(self.uploadDict as! [String : Any])
        
        var content = ""
        headerModel?.content.forEach({ (make) in
            print(make.text)
            content += "/" + make.text
            
            make.text = ""
            make.text1 = ""
        })
        
    
        let goodsname = uploadDict["goodsname"] as! String
        let goodsnum = uploadDict["goodsnum"]  as! String
        let volume = uploadDict["volume"]  as! String
        let weight = uploadDict["weight"]  as! String
        
        let item = JSFormModel()
        item.icon = "icon_name"
        item.name = goodsname
        item.text = "\(goodsnum)件/\(weight)公斤/\(volume)方"

        showModel.content.append(item)

        
        self.uploadDict.removeAllObjects()
        tableView.reloadData()
    }
    @objc func subItemClick(){
        if self.arr.count<=0 {
            JSShowMessage.showTipMsg("请添加货物", time: 0.5)
        }else
        {
            block!(self.arr)
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    /// 验证货物信息是否完整
    /// - Returns: 验证信息
    func validateValue() -> String{
        /**
         goodsname = 2323;
         goodsnum = "1.0";
         packway = 1;
         unit = "\U4ef6";
         unitPrice = 33333;
         volume = "4.0";
         weight = "4.0";
         */
        
        let goodsname = self.uploadDict.object(forKey: "goodsname") as? String
        let goodsnum = self.uploadDict.object(forKey: "goodsnum") as? String
        let volume = self.uploadDict.object(forKey: "volume") as? String
        let weight = self.uploadDict.object(forKey: "weight") as? String
        guard goodsname != nil && goodsname!.count>0 else {            return "请输入货物名称"        }
        
        guard goodsnum != nil && goodsnum!.count>0 else {            return "请输入货物数量"        }
        guard weight != nil && weight!.count>0 else {            return "请输入货物重量"        }
        guard volume != nil && volume!.count>0 else {            return "请输入货物体积"        }
        
        return ""
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.edgesForExtendedLayout = .init()
        let subItem:UIBarButtonItem = UIBarButtonItem(title: "确定", titleColor: .systemBlue, titleFont: UIFont.systemFont(ofSize: 16), titleEdgeInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0), target: self, action: #selector(subItemClick))
        self.navigationItem.rightBarButtonItem = subItem
        loadDataWithFileName(fileName: "SendvehicleGoods.json")
        
        checkHaveEmptyField { (String) in
            
        }
        
        datas.insert(showModel, at: 0)
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets(top: 20, left: 20, bottom: 0, right: 20))
        }
        
        self.tableView.reloadData()
        // Do any additional setup after loading the view.
        
        let tableFooterView = UIView()
        tableFooterView.frame = CGRect(x: 0, y: 0, width: 0, height: 100)
        
        tableView.tableFooterView = tableFooterView
        
        tableFooterView.addSubview(iconBtn)
        tableFooterView.addSubview(noteLab)
        iconBtn.snp.makeConstraints { (make) in
            make.top.equalTo(10)
            make.left.equalTo(tableFooterView.snp.centerX).offset(30)
            make.width.equalTo(80)
            make.height.equalTo(40)
        }
        noteLab.snp.makeConstraints { (make) in
            make.top.equalTo(iconBtn.snp.bottom).offset(5)
            make.left.equalTo(20)
            
        }
        
    }
    
    
    func rightBarButtonItemClicked()  {
        if isEdit {
            self.tableView.setEditing(false, animated: true)
            isEdit = false
        } else {
            self.tableView.setEditing(true, animated: true)
            isEdit = true
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return datas.count
    }
    ///UITableViewDataSource
    //返回cell的行数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let headerModel = self.datas[section] as? JSFormHeaderModel
        return headerModel!.content.count
        
    }
    //返回cell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //        let Identifier:String = "UITableViewCell"
        //        var cell = tableView.dequeueReusableCell(withIdentifier: Identifier)
        //
        //        //        let cell = tableView.dequeueReusableCell(withIdentifier: Identifier, for: indexPath)
        //        if cell==nil {
        //            cell = UITableViewCell(style: .default, reuseIdentifier: Identifier)
        //            //cell = tableViewCell
        //        }
        //        cell?.textLabel?.text = self.datas[indexPath.row] as? String
        //        //        cell?.imageView?.image = UIImage(named: self.datas[indexPath.row] as! String)
        //        return cell!
        if indexPath.section == 0 {
            let Identifier:String = "JSGoodsFormsCell"
            var cell = tableView.dequeueReusableCell(withIdentifier: Identifier) as? JSBaseViewCell
            
            //        let cell = tableView.dequeueReusableCell(withIdentifier: Identifier, for: indexPath)
            if cell == nil {
                cell = JSGoodsFormsCell(style: .default, reuseIdentifier: Identifier)
                //cell = tableViewCell
            }
            //                    cell?.textLabel?.text = self.datas[indexPath.row] as? String
            //        cell?.imageView?.image = UIImage(named: self.datas[indexPath.row] as! String)
            let headerModel = self.datas[indexPath.section] as? JSFormHeaderModel
            let model:JSFormModel = headerModel!.content[indexPath.row]
            cell!.initWith(Model: model, VC: self)
            return cell!
        }
        let headerModel = self.datas[indexPath.section] as? JSFormHeaderModel
        let model:JSFormModel = headerModel!.content[indexPath.row]
        
        let cell = tableView.dequeueReusableCell(withIdentifier: model.cellID as String, for: indexPath) as! JSBaseViewCell
        cell.initWith(Model: model, VC: self)
        
        return cell
    }
    //
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
    {
        if indexPath.section == 0 {
            return 50
        }
        let headerModel = self.datas[indexPath.section] as? JSFormHeaderModel
        let model:JSFormModel = headerModel!.content[indexPath.row]
        return model.height
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        print(indexPath)
        let cell : JSBaseViewCell = tableView.cellForRow(at: indexPath) as! JSBaseViewCell
        
        //        JSBaseViewCell  *cell = [tableView cellForRowAtIndexPath:indexPath];
        
        self.view.endEditing(true)
        cell.doSomething()
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section==0 {
            return nil
        }
        
        var headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "FXFormHeaderViewID") as? JSFormHeaderView
        if headerView == nil {
            headerView = JSFormHeaderView(reuseIdentifier: "FXFormHeaderViewID")
        }
        
        let headerModel = self.datas[section] as? JSFormHeaderModel
        headerView?.model = (headerModel?.header)!
        headerView?.editBtn.isHidden = true
        
        //
        //        let name = headerModel?.content.first?.text
        //        let tel = headerModel?.content[1].text
        //        let content = name! + "  " + tel!
        //        let nameAttribute = [NSAttributedString.Key.foregroundColor: UIColor.black,
        //                           NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 18)] as [NSAttributedString.Key : Any]
        //        let telAttribute = [NSAttributedString.Key.foregroundColor: UIColor.lightGray,
        //                           NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14)] as [NSAttributedString.Key : Any]
        //        let attString = NSMutableAttributedString(string: content)
        //        attString.addAttributes(nameAttribute, range: NSRange.init(location: 0, length: name!.count))
        //        attString.addAttributes(telAttribute, range: NSRange.init(location: content.count-tel!.count, length: tel!.count))
        //
        //        headerView?.content.attributedText = headerModel!.isFolding ? attString:nil
        
        
        return headerView
    }
    
    @objc func headViewClick() -> Void {
        if showAll {
            showAll = false
            
        }else{
            showAll = true
            
        }
        let set:IndexSet = IndexSet.init(integer: 0)
        tableView.reloadSections(set as IndexSet, with: .fade)
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section==0 {
            return CGFloat.leastNormalMagnitude
        }
        return  sectionHeaderHeight
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        let headerModel = self.datas[indexPath.section] as? JSFormHeaderModel
        let model:JSFormModel = headerModel!.content[indexPath.row]
//        print(model.name)
//        print(model.height)
        
        return  model.height
    }
    
    
    func checkHaveEmptyField(block1 : (_ result:Bool,_ message : String)->Void){
        
        for field in self.datas {
            let field = field as? JSFormModel
            if field?.cellType == JSCellType.FXCellTypeMeida.rawValue {
                if field?.medias.count == 1 {
                    block1(true, "请上传"+field!.name)
                    return
                }
            }else
            {
                if (field?.text.count)!<=0 {
                    let prefix:String = (field?.cellType == JSCellType.FXCellTypeArrow.rawValue || field?.cellType == JSCellType.FXCellTypeCheckBox.rawValue) ? "请选择" : "请输入"
                    block1(true, prefix+field!.name)
                    return
                }else
                {
                    self.uploadDict.setValue(field?.text, forKey: (field?.key)!)
                }
            }
            
        }
        block1(false,"")
    }
    //可被编辑
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        if indexPath.section == 0 {
            return true
        }
        return false
    }
    
    //确定编辑模式（默认是滑动删除模式）
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete
    }
    //具体编辑操作（默认删除操作）
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        //
        //        datas.removeObject(at: indexPath.row)
        let headerModel = self.datas[indexPath.section] as? JSFormHeaderModel
        headerModel?.content.remove(at: indexPath.row)
        self.arr.remove(at: indexPath.row)
        //
        tableView.deleteRows(at: [indexPath], with: .top)
    }
    //    //允许移动某一行
    //    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    //        return true
    //    }
    //
    //    //实现排序
    //    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    //        //后面加as。。。
    //        let object:AnyObject = self.dataArray[sourceIndexPath.row] as AnyObject
    //        //
    //        self.dataArray.removeObject(at: sourceIndexPath.row)
    //        self.dataArray.insert(object, at: destinationIndexPath.row)
    //
    //
    //    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
}
